import { useState, useEffect, useCallback } from 'react';
import {
  X,
  RefreshCw,
  CheckCircle,
  XCircle,
  Clock,
  AlertTriangle,
  ExternalLink,
  Download,
} from 'lucide-react';
import videoService from '../services/videoService';
import { toast } from '../stores/toastStore';

interface VideoStatus {
  video_id: string;
  status: string;
  progress: number;
  message: string;
  created_at: number;
  duration?: number;
  video_url?: string;
  thumbnail_url?: string;
  caption_url?: string;
  error?: Record<string, unknown>;
}

interface VideoStatusTrackerProps {
  videoId: string;
  onClose: () => void;
}

export default function VideoStatusTracker({ videoId, onClose }: VideoStatusTrackerProps) {
  const [videoStatus, setVideoStatus] = useState<VideoStatus | null>(null);
  const [loading, setLoading] = useState(false);
  const [lastChecked, setLastChecked] = useState<Date | null>(null);

  const statusIcons = {
    pending: <Clock className="w-5 h-5 text-yellow-600" />,
    processing: <RefreshCw className="w-5 h-5 text-blue-600 animate-spin" />,
    completed: <CheckCircle className="w-5 h-5 text-green-600" />,
    failed: <XCircle className="w-5 h-5 text-red-600" />,
  };

  const statusColors = {
    pending: 'bg-yellow-50 border-yellow-200 text-yellow-800',
    processing: 'bg-blue-50 border-blue-200 text-blue-800',
    completed: 'bg-green-50 border-green-200 text-green-800',
    failed: 'bg-red-50 border-red-200 text-red-800',
  };

  const checkStatus = useCallback(async () => {
    try {
      setLoading(true);
      const status = await videoService.checkVideoStatusFromAPI(videoId);
      setVideoStatus(status);
      setLastChecked(new Date());
    } catch (error) {
      console.error('Failed to check video status:', error);
      const errorMessage = error instanceof Error ? error.message : '查询状态失败';
      toast.error(`查询状态失败: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
  }, [videoId]);

  const downloadVideo = async () => {
    if (!videoStatus?.video_url) return;

    try {
      const link = document.createElement('a');
      link.href = videoStatus.video_url;
      link.download = `video_${videoId}.mp4`;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('Failed to download video:', error);
      toast.error('视频下载失败');
    }
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN');
  };

  const formatDuration = (seconds: number) => {
    if (seconds < 60) return `${seconds.toFixed(1)} 秒`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toFixed(0).padStart(2, '0')}`;
  };

  // 初始加载
  useEffect(() => {
    checkStatus();
  }, [checkStatus]);

  // 自动刷新（对于处理中的视频）
  useEffect(() => {
    if (!videoStatus || videoStatus.status === 'completed' || videoStatus.status === 'failed') {
      return;
    }

    const interval = setInterval(() => {
      checkStatus();
    }, 10000); // 每10秒检查一次

    return () => clearInterval(interval);
  }, [videoStatus, checkStatus]);

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-hidden">
        {/* Header */}
        <div className="p-6 border-b flex justify-between items-center">
          <div>
            <h2 className="text-xl font-bold text-gray-900">视频生成状态</h2>
            <p className="text-sm text-gray-600 font-mono">视频ID: {videoId}</p>
          </div>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-700 cursor-pointer">
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto">
          {!videoStatus ? (
            <div className="flex items-center justify-center py-8">
              <RefreshCw className="w-6 h-6 text-blue-500 animate-spin mr-2" />
              <span className="text-gray-600">正在查询状态...</span>
            </div>
          ) : (
            <div className="space-y-6">
              {/* Status Card */}
              <div
                className={`p-4 rounded-lg border ${statusColors[videoStatus.status as keyof typeof statusColors] || 'bg-gray-50 border-gray-200 text-gray-800'}`}
              >
                <div className="flex items-center gap-3 mb-2">
                  {statusIcons[videoStatus.status as keyof typeof statusIcons] || (
                    <AlertTriangle className="w-5 h-5 text-gray-600" />
                  )}
                  <span className="font-semibold text-lg">{videoStatus.message}</span>
                </div>
                <div className="ml-8">
                  <p className="text-sm">进度: {videoStatus.progress}%</p>
                  <p className="text-sm">状态: {videoStatus.status}</p>
                </div>
              </div>

              {/* Video Info */}
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-gray-50 p-4 rounded-lg">
                  <h3 className="font-medium text-gray-900 mb-2">创建时间</h3>
                  <p className="text-sm text-gray-700">{formatDate(videoStatus.created_at)}</p>
                </div>
                {videoStatus.duration && (
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <h3 className="font-medium text-gray-900 mb-2">视频时长</h3>
                    <p className="text-sm text-gray-700">{formatDuration(videoStatus.duration)}</p>
                  </div>
                )}
              </div>

              {/* Error Details */}
              {videoStatus.status === 'failed' && videoStatus.error && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                  <h3 className="font-medium text-red-900 mb-2 flex items-center gap-2">
                    <XCircle className="w-5 h-5" />
                    错误详情
                  </h3>
                  <pre className="text-sm text-red-800 bg-red-100 p-3 rounded border overflow-auto">
                    {JSON.stringify(videoStatus.error, null, 2)}
                  </pre>
                </div>
              )}

              {/* Video Preview and Actions */}
              {videoStatus.status === 'completed' && (
                <div className="space-y-4">
                  {videoStatus.thumbnail_url && (
                    <div className="bg-gray-50 p-4 rounded-lg">
                      <h3 className="font-medium text-gray-900 mb-2">视频预览</h3>
                      <img
                        src={videoStatus.thumbnail_url}
                        alt="Video thumbnail"
                        className="w-full max-w-md rounded border"
                        onError={e => {
                          e.currentTarget.style.display = 'none';
                        }}
                      />
                    </div>
                  )}

                  <div className="flex gap-3">
                    {videoStatus.video_url && (
                      <>
                        <button
                          onClick={downloadVideo}
                          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer"
                        >
                          <Download className="w-4 h-4" />
                          下载视频
                        </button>
                        <a
                          href={videoStatus.video_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                        >
                          <ExternalLink className="w-4 h-4" />
                          在新标签页观看
                        </a>
                      </>
                    )}
                  </div>
                </div>
              )}

              {/* Last Checked Info */}
              {lastChecked && (
                <div className="text-center text-sm text-gray-500">
                  最后检查时间: {lastChecked.toLocaleString('zh-CN')}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-6 border-t flex justify-between items-center">
          <button
            onClick={checkStatus}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            {loading ? '检查中...' : '刷新状态'}
          </button>
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 cursor-pointer"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
}
